<template>
  <div class="table">
    <div class="crumbs"><i class="el-icon-tickets"></i>歌手————歌曲管理</div>
    <div class="container">
      <div class="handle-box">
        <el-input
          v-model="select_word"
          class="handle-input mr10"
          size="small"
          placeholder="请输入歌曲名字"
        ></el-input>
        <el-button
          type="primary"
          size="small"
          @click="centerDialogVisible = true"
          >添加歌曲</el-button
        >
        <el-button type="primary" size="small" @click="delAll"
          >批量删除</el-button
        >
      </div>
    </div>
    <el-table
      ref="multipleTable"
      border
      size="small"
      style="width: 100%"
      height="580px"
      :data="data"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column label="歌曲图片" width="110" align="center">
        <template v-slot="scope">
          <div class="song-img">
            <el-image
              :fit="fits"
              :src="getUrl(scope.row.pic)"
              alt=""
              style="width: 100%"
            ></el-image>
          </div>
          <div class="play" @click="setSongUrl(scope.row.url, scope.row.name)">
            <div v-if="toggle !== scope.row.name">
              <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-bofanganniu"></use>
              </svg>
            </div>
            <div v-if="toggle == scope.row.name">
              <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-zanting"></use>
              </svg>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="歌手-歌名"
        width="120"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="introduction"
        label="专辑"
        width="150"
        align="center"
      ></el-table-column>
      <el-table-column label="歌词" align="center">
        <template slot-scope="scope">
          <ul style="height: 100px; overflow: scroll">
            <li
              v-for="(item, index) in parseLyric(scope.row.lyric)"
              :key="index"
            >
              {{ item }}
            </li>
          </ul>
        </template>
      </el-table-column>
      <el-table-column label="资源更新" width="100" align="center">
        <template v-slot="scope">
          <el-upload
            class="upload-demo"
            :action="uploadUrl(scope.row.id)"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-button size="small">更新图片</el-button>
          </el-upload>
          <br />
          <el-upload
            class="upload-demo change"
            :action="uploadSongUrl(scope.row.id)"
            :show-file-list="false"
            :on-success="handleSongSuccess"
            :before-upload="beforeSongUpload"
          >
            <el-button size="small">更新歌曲</el-button>
          </el-upload>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template v-slot="scope">
          <el-button size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <!-- 添加歌曲弹出框 -->
    <el-dialog
      title="添加歌曲"
      :visible.sync="centerDialogVisible"
      width="400px"
      center
    >
      <div>
        <label>歌名</label>
        <el-input v-model="song.name" type="text" name="name"></el-input>
      </div>
      <div>
        <label>专辑</label>
        <el-input
          type="text"
          v-model="song.introduction"
          name="introduction"
        ></el-input>
      </div>
      <div>
        <label>歌词</label>
        <el-input type="text" v-model="song.lyric" name="lyric"></el-input>
      </div>
      <div>
        <label>歌曲上传</label>
        <input type="file" name="file" ref="myFile" />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="centerDialogVisible = false"
            >取 消</el-button
          >
          <el-button type="primary" size="small" @click="addSong"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 编辑歌曲弹出框 -->
    <el-dialog title="修改歌曲" :visible.sync="editVisible" width="450px">
      <el-form ref="editorForm" :model="editorForm" label-width="100px">
        <el-form-item label="歌手-歌名" size="small" prop="name">
          <el-input
            v-model="editorForm.name"
            placeholder="歌手-歌名"
          ></el-input>
        </el-form-item>
        <el-form-item label="专辑" size="small" prop="introduction">
          <el-input
            v-model="editorForm.introduction"
            placeholder="专辑"
          ></el-input>
        </el-form-item>
        <el-form-item label="歌词" size="small" prop="lyric">
          <el-input
            type="textarea"
            v-model="editorForm.lyric"
            placeholder="歌词"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="editVisible = false">取 消</el-button>
          <el-button type="primary" size="small" @click="saveEdit"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 删除歌曲弹出框 -->
    <el-dialog title="删除歌曲" :visible.sync="delVisible" width="400px">
      <div class="center">删除不可恢复，是否确定删除？</div>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="delVisible = false">取 消</el-button>
          <el-button type="primary" size="small" @click="deleteRow"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { mixin } from "../mixins";
import { mapGetters } from "vuex";
import '@/assets/js/iconfont.js';
import { songOfSingerId, updateSong, delSong } from "../api/index";
export default {
  mixins: [mixin],
  data() {
    return {
      //接受歌手的参数
      singerId: "",
      singerName: "",
      fits: "cover",
      //添加歌手对话框
      centerDialogVisible: false,
      //编辑对话框
      editVisible: false,
      //删除对话框
      delVisible: false,
      tempDate: [],
      select_word: "",

      idx: -1,

      //编辑框
      editorForm: {
        // 编辑框信息
        id: "",
        name: "",
        introduction: "",
      },

      //添加歌曲
      song: {},
      registerForm: {
        // 添加框信息
        name: "",
        singerName: "",
        lyric: "",
        introduction: "",
      },
      tableData: [],

      //批量删除数组
      multipleSelection: [],
      //播放器显示图标状态
      toggle:false,

      pageSize: 4, // 页数
      currentPage: 1, // 当前页
    };
  },
  computed: {
    ...mapGetters([
      'isPlay' // 播放状态
    ]),
    playIcon () {
      if (this.isPlay) {
        return this.ZANTING
      } else {
        return this.BOFANG
      }
    },
    //计算当前搜索结果的数据
    data() {
      return this.tableData.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
  },
  created() {
    const _this = this;
    _this.singerId = _this.$route.query.id;
    _this.singerName = _this.$route.query.name;
    _this.getData();
  },
  destroyed(){
    this.$store.commit('setIsPlay',false);
  },
  unmounted () {
    this.$store.commit('setIsPlay', false)
  },
  methods: {
    //获取当前页
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    //更新图片
    uploadUrl(id) {
      return `${this.$store.state.HOST}/song/updateSongPic?id=${id}`;
    },
    //更新歌曲地址
    uploadSongUrl(id) {
      return `${this.$store.state.HOST}/song/updateSongUrl?id=${id}`;
    },
    // 获取歌曲
    getData() {
      const _this = this;
      _this.tableData = [];
      _this.tempDate = [];
      songOfSingerId(_this.singerId).then((res) => {
        _this.tableData = res;
        _this.tempDate = res;
        _this.currentPage = 1;
      });
    },
    // 添加歌曲
    addSong() {
      const _this = this;
      var formData = new FormData();
      formData.append("singer_id", _this.singerId);
      _this.song.name = _this.singerName+"-"+_this.song.name;
      formData.append("name", _this.song.name);
      if(_this.song.introduction == ""){
        _this.song.introduction = "";
      }
      formData.append("introduction", _this.song.introduction);
      if (_this.song.lyric == "" || _this.song.lyric == null) {
        _this.song.lyric = "[00:00:00]暂无歌词";
      }
      formData.append("lyric", _this.song.lyric);
      formData.append("mpFile", _this.$refs.myFile.files[0]);
      _this
        .$axios({
          method: "post",
          url: "http://localhost:1109/song/add",
          data: formData,
          headers: {
            "content-type": "multipart/form-data",
          },
        })
        .then((res) => {
          if (res.data.code == 1) {
            _this.getData();
            _this.$notify({
              title: "添加歌曲成功",
              type: "success",
            });
          } else {
            _this.$notify({
              title: "添加歌曲失败",
              type: "error",
            });
          }
        });
      _this.centerDialogVisible = false;
    },

    //编辑
    handleEdit(row) {
      this.editVisible = true;
      this.editorForm = {
        id: row.id,
        name: row.name,
        introduction: row.introduction,
        lyric: row.lyric,
      };
    },
    // 保存编辑
    saveEdit() {
      const _this = this;
      updateSong(_this.editorForm)
        .then((res) => {
          if (res.code === 1) {
            _this.getData();
            _this.$notify({
              title: "编辑成功",
              type: "success",
            });
          } else {
            _this.$notify({
              title: "编辑失败",
              type: "error",
            });
          }
        })
        .catch((err) => {
          console.error(err);
        });
      _this.editVisible = false;
    },
    //删除一首歌
    deleteRow() {
      const _this = this;
      let id = _this.idx;
      delSong(id).then((res) => {
        if (res.code === 1) {
          _this.getData();
          _this.$notify({
            title: "删除成功",
            type: "success",
          });
          _this.delVisible = false;
        } else {
          _this.$notify({
            title: "删除失败",
            type: "error",
          });
        }
      });
    },

    // 解析歌词
    parseLyric(text) {
      let lines = text.split("\n");
      let pattern = /\[\d{2}:\d{2}.(\d{3}|\d{2})\]/g;
      let result = [];
      // 对于歌词格式不对的特殊处理
      if (!/\[.+\]/.test(text)) {
        return [text];
      }
      for (let item of lines) {
        if (pattern.test(item)) {
          let value = item.replace(pattern, ""); // 存歌词
          result.push(value);
        }
      }
      return result;
    },
    //播放歌曲
    setSongUrl (url, name) {
      this.$store.commit('setUrl', this.$store.state.HOST + url)
      this.toggle = name
      if (this.isPlay) {
        this.$store.commit('setIsPlay', false)
      } else {
        this.$store.commit('setIsPlay', true)
      }
    },
  },
  
  watch: {
    //搜索框内容监听
    select_word: function () {
      if (this.select_word === "") {
        this.tableData = this.tempDate;
      } else {
        this.tableData = [];
        for (let item of this.tempDate) {
          if (item.name.includes(this.select_word)) {
            this.tableData.push(item);
          }
        }
      }
    },
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}
.handle-input {
  width: 300px;
  display: inline-block;
}
.song-img {
  width: 100%;
  height: 80px;
  border-radius: 5px;
  margin-bottom: 5px;
  overflow: hidden;
}
.pagination {
  display: flex;
  justify-content: center;
}
.play{
  position: absolute;
  z-index: 100;
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  top: 18px;
  left: 15px;
}
.icon{
  width: 2em;
  height: 2em;
  color: white;
  fill: currentColor;
  overflow: hidden;
}
</style>